package cn.colat.micse.gateway.filter;

import cn.colat.micse.gateway.utils.NanoIdUtil;
import cn.dev33.satoken.same.SaSameUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关处添加Same-Token
 */
@Slf4j
@Component
public class ForwardAuthFilter implements GlobalFilter {
    public static final String TRACE_ID = "traceId";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = SaSameUtil.getToken();
        String traceId = NanoIdUtil.randomNanoId();
        MDC.put(TRACE_ID, traceId);
        log.info("{} = {}", SaSameUtil.SAME_TOKEN, token);
        ServerHttpRequest request = exchange.getRequest()
                .mutate()
                // 网关统一鉴权，禁止直接访问子服务 为请求追加 Same-Token 参数
                .header(SaSameUtil.SAME_TOKEN, token)
                // 添加 traceId 追踪请求
                .header(TRACE_ID, traceId)
                .build();
        ServerWebExchange newEx = exchange.mutate()
                .request(request)
                .build();
        return chain.filter(newEx);
    }
}
